package com.chanjiedata.changbs.module.main;

/**
 * 文件名 : QrCodeFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/6 17:44
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */

import android.Manifest;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseFragment;
import com.chanjiedata.changbs.help.GlideHelper;
import com.chanjiedata.changbs.help.PermissionHelper;
import com.chanjiedata.changbs.help.UserHelper;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Memberinviter;
import com.chanjiedata.changbs.utlis.ImageUtil;
import com.chanjiedata.changbs.utlis.PreferenceSettings;
import com.chanjiedata.changbs.utlis.SaveViewToImageUtil;
import com.google.protobuf.InvalidProtocolBufferException;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by AndroidIntexh1 on 2018/10/30.
 */

public class QrCodeFragment extends BaseFragment {

    private static final String CURRE_QR_BG = "CURRE_QR_BG";
    @BindView(R.id.iv_share)
    TextView ivShare;
    @BindView(R.id.iv_qr_bg)
    ImageView ivQrBg;
    @BindView(R.id.iv_qr_code)
    ImageView ivQrCode;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_invite_code)
    TextView tvInviteCode;
    @BindView(R.id.tv_id)
    TextView tvId;
    @BindView(R.id.rl_qr_bg)
    RelativeLayout rlQrBg;


    private PopupWindow mPopupWindow;
    private Memberinviter.get_my_qrcode_inviter infoBean;
    private List<Memberinviter.get_my_qrcode_inviter.List> bgBeanList = new ArrayList<>();
    private int currentBg = 0;
    private Unbinder unbinder;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_live;
    }


    @Override
    protected void initView() {
        ivShare.setOnClickListener(view -> {
            more();
        });
        if (UserHelper.isLogin()) {
            loadData();
        }


    }

    @Override
    protected void init() {
        rlQrBg.setTag(1);
    }

    private void more() {
        if (mPopupWindow == null) {
            View popView = View.inflate(mContext, R.layout.more_layout, null);
            mPopupWindow = new PopupWindow(popView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
            mPopupWindow.setOutsideTouchable(true);
            ColorDrawable dw = new ColorDrawable(Color.parseColor("#00000000"));
            // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
            // 我觉得这里是API的一个bug
            mPopupWindow.setBackgroundDrawable(dw);
            popView.findViewById(R.id.save_image).setOnClickListener(view -> {
                PermissionHelper.getInstance().getPermission(getActivity(), new PermissionHelper.PermissionCallBack() {
                    @Override
                    public void onSuccess() {
                        Bitmap viewBitmap = SaveViewToImageUtil.getViewBitmap(rlQrBg);
                        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "changpay";
                        String fileName = System.currentTimeMillis() + ".jpg";
                        boolean b = ImageUtil.saveImageToGallery(mContext, viewBitmap, storePath, fileName);
                        if (b) {
                            showToast("保存成功");
                            mPopupWindow.dismiss();
                        }

                    }

                    @Override
                    public void onFail() {
                        showToast("获取权限失败");
                    }
                }, Manifest.permission.WRITE_EXTERNAL_STORAGE);


            });
            popView.findViewById(R.id.change_bg).setOnClickListener(view -> {
                changeBg();
                mPopupWindow.dismiss();
            });
        }
        mPopupWindow.showAsDropDown(ivShare);
    }

    private void changeBg() {
        int size = bgBeanList.size();
        int i = currentBg + 1;
        if (i > size - 1)  // 加载第一个
        {
            currentBg = 0;
            PreferenceSettings.setString(CURRE_QR_BG, bgBeanList.get(0).getAdvId());
            GlideHelper.INSTANCE.loadImage(ivQrBg, bgBeanList.get(0).getAdvCode());
        } else {
            currentBg = i;
            PreferenceSettings.setString(CURRE_QR_BG, bgBeanList.get(i).getAdvId());
            GlideHelper.INSTANCE.loadImage(ivQrBg, bgBeanList.get(i).getAdvCode());
        }
    }


    private void loadData() {
        // 加载二维码数据

        NetworkManager.INSTANCE.post(Apis.get_memberinviter, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                infoBean = Memberinviter.get_my_qrcode_inviter.parseFrom(response);
                tvName.setText(infoBean.getMemberName());
                tvId.setText("ID：" + infoBean.getMemberId());
                tvInviteCode.setText("邀请码：" + infoBean.getInviterCode());
                GlideHelper.INSTANCE.loadImage(ivQrCode, infoBean.getQrcodeUrl());
                GlideHelper.INSTANCE.loadAvatar(ivHead, infoBean.getMemberAvatar());
                bgBeanList = infoBean.getImgBgListList();
                loadQrBg();
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    /**
     * 加载背景图片
     */
    private void loadQrBg() {
        // 1 读取缓存中的数据
        String old_bg = PreferenceSettings.getString(CURRE_QR_BG, "");
        if (TextUtils.isEmpty(old_bg))  // 为空
        {
            // 写入背景id
            Memberinviter.get_my_qrcode_inviter.List qrBgBean = bgBeanList.get(0);
            PreferenceSettings.setString(CURRE_QR_BG, qrBgBean.getAdvId());
            GlideHelper.INSTANCE.loadImage(ivQrBg, qrBgBean.getAdvCode());
            currentBg = 0;
        } else {
            // 查找当前list中是否有保存id
            for (int i = 0; i < bgBeanList.size(); i++) {
                Memberinviter.get_my_qrcode_inviter.List bgBean = bgBeanList.get(i);
                if (bgBean.getAdvId().equals(old_bg)) {
                    currentBg = i;
                    PreferenceSettings.setString(CURRE_QR_BG, bgBean.getAdvId());
                    GlideHelper.INSTANCE.loadImage(ivQrBg, bgBean.getAdvCode());
                    break;
                }
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
    }


}
